package jsonTest;

import com.alibaba.fastjson.JSON;
import pojo.Result;
import pojo.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("serv");
        ArrayList<User> list = new ArrayList<>();
        User user1 = new User("仗义", "123");
        User user2 = new User("仗义2", "1323");
        User user3 = new User("仗4义", "123");
        User user4 = new User("仗义5", "12563");
        Collections.addAll(list, user1, user2, user3, user4);
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        BufferedReader br = request.getReader();
        String json = br.readLine();
        System.out.println("json"+json);
        User user = JSON.parseObject(json, User.class);
        System.out.println("user:"+user);
        Result r = new Result();
        if (user.getUsername().equals("张三") && user.getPassword().equals("123")) {
            r.setMsg("用户列表如下：");
            r.setFlag(true);
            r.setData(list);
        } else {
            r.setMsg("密码或账号错误，登录失败");
            r.setFlag(false);
        }
        String resultJson = JSON.toJSONString(r);
        System.out.println("resultjosn:"+resultJson);
        response.getWriter().println(resultJson);
    }
}
